<?php

namespace App\Store\Controllers\Basic;

use App\Common\Services\CommonExcelExport;
use App\Store\Models\Sysset\Score;
use App\Store\Services\Goods\Goods;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Basic\GoodsCategory;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCabinetgroup;
use App\Store\Models\Basic\GoodsMetal;
use App\Store\Models\Basic\GoodsStone;
use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Validate\Basic\GoodsCategory as ValidateBasicGoodsCategory;

use App\Store\Services\Excel\DownloadTemp;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 商品类别信息
 */
class GoodsCategoryController extends Controller
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        $list = GoodsCategory::getList($request);

        if ($request->withprice == 1) {
            $accountinfo = StoreCommon::getCurrentAccountinfo($request);
            $cp_id = $accountinfo['cp_id'];

            foreach ($list['list'] as &$val) {
                $val['priceinfo'] = GoodsGlodprice::where(['cp_id' => $cp_id, 'store_id' => $val['store_id'], 'goods_category_id' => $val['id'], 'is_del' => 1])
                    ->where('date_str', '<=', date('Y-m-d'))->orderBy('date_str', 'desc')->first();
            }
        }

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 获取商品列表名称
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCate(Request $request)
    {
        $store_id = $request->store_id ?? 0;//下拉单选搜索
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $cateList = GoodsCategory::query()
            ->when($store_id > 0, function ($query) use ($store_id) {
                $query->where('store_id', $store_id);
            })
            ->where('cp_id', $cp_id)
            ->where('is_del', 1)
            ->get()
            ->pluck('category_name')
            ->toArray();
        $cateList = array_values(array_unique($cateList));

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $cateList]);

    }


    public function getlistbystore(Request $request)
    {
        $list = GoodsCategory::getListByStore($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }


    /**
     * 获取详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsCategory::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 新增
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['store_ids', 'category_name', 'goods_cabinetgroup_id', 'goods_metal_id', 'is_recovery', 'is_sujin', 'is_virtually', 'is_maintenance_price', 'is_gram', 'remark', 'price_discount']);

        $Validate = new ValidateBasicGoodsCategory();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $store_ids = $req_data['store_ids'];

        //修改goods_metal_id 材质 非必填 2024.11.15
        if (!isset($req_data['goods_metal_id']) || empty($req_data['goods_metal_id'])) {
            $req_data['goods_metal_id'] = 0;
        }

        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);

        if ($req_data['is_sujin'] != $req_data['is_gram']) {
            return response()->json(['code' => '001', 'msg' => '是否素金和是否克算的值需要保持一致']);
        }

        if ($req_data['is_sujin'] == 1 && $req_data['is_virtually'] == 1) {
            return response()->json(['code' => '001', 'msg' => '素金类不可为虚拟商品']);
        }


        if (count($store_ids) <= 0) {

            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $data_data = [];
        foreach ($store_ids as $store_id) {

            $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id']])->first();
            if (!$storeinfo) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }
            $isexist = GoodsCategory::where([['category_name', $req_data['category_name']], ['store_id', $store_id], ['cp_id', $accountinfo['cp_id']], ['is_del', 1]])->first();
            if ($isexist) {
                return response()->json(['code' => '001', 'msg' => $storeinfo->store_name . '门店下存在此商品类别名称']);
            }

            $data = $req_data;
            unset($data['store_ids']);
            $data['store_id'] = $store_id;
            $data['price_discount'] = empty($req_data['price_discount']) ? 0 : $req_data['price_discount'];
            $data['create_account_id'] = $accountinfo['id'];
            $data['update_account_id'] = $accountinfo['id'];
            $data['create_account_real_name'] = $accountinfo['real_name'];
            $data['update_account_real_name'] = $accountinfo['real_name'];
            $data['cp_id'] = $accountinfo['cp_id'];
            $data['create_at'] = time();
            $data['update_at'] = time();
            $data_data[] = $data;
        }
        GoodsCategory::insert($data_data);
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $req_data = $request->only(['id', 'category_name', 'goods_cabinetgroup_id', 'goods_metal_id', 'is_recovery', 'is_sujin', 'is_virtually', 'is_maintenance_price', 'is_gram', 'remark', 'price_discount']);

        $Validate = new ValidateBasicGoodsCategory('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        if ($req_data['is_sujin'] != $req_data['is_gram']) {
            return response()->json(['code' => '001', 'msg' => '是否素金和是否克算的值需要保持一致']);
        }

        if ($req_data['is_sujin'] == 1 && $req_data['is_virtually'] == 1) {
            return response()->json(['code' => '001', 'msg' => '素金类不可为虚拟商品']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsCategory::where([['id', $req_data['id']], ['cp_id', $cp_id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $isexist = GoodsCategory::where([['id', '<>', $req_data['id']], ['category_name', $req_data['category_name']], ['store_id', $info->store_id], ['cp_id', $accountinfo['cp_id']], ['is_del', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '商品类别名称不允许重复']);
        }

        $data = $req_data;
        unset($data['id']);
        $data['update_at'] = time();
        $data['update_account_id'] = $accountinfo['id'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        $data['price_discount'] = empty($req_data['price_discount']) ? 0 : $req_data['price_discount'];
        GoodsCategory::where(['id' => $req_data['id']])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 删除
     */
    public function dodel(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = GoodsCategory::where([['id', $id], ['cp_id', $cp_id], ['is_del', 1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $res = (new Goods())->checkGoods('goods_category_id', $id);

        if ($res) {
            return response()->json(['code' => '001', 'msg' => '此类别下有商品不能删除']);
        }

        $glod = GoodsGlodprice::query()->where('goods_category_id', $id)->where('is_del', 1)->first();

        if (!empty($glod)) {
            return response()->json(['code' => '001', 'msg' => '此类别下有金价在使用，不能删除']);
        }

        $score = Score::where('goods_category_id', $id)->first();
        if (!empty($score)) {
            return response()->json(['code' => '001', 'msg' => '积分设置中正在使用该类别，不能删除']);
        }


        GoodsCategory::where([['id', $id]])->update(['is_del' => 2, 'del_at' => time()]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function dodelmore(Request $request)
    {
        $ids = $request->ids;//下拉多选搜索
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        if (count($ids) <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择需要删除的记录']);
        }

        foreach ($ids as $id) {
            $res = (new Goods())->checkGoods('goods_category_id', $id);
            if ($res) {
                return response()->json(['code' => '001', 'msg' => '此类别下有商品不能删除']);
            }

            $glod = GoodsGlodprice::query()->where('goods_category_id', $id)->where('is_del', 1)->first();

            if (!empty($glod)) {
                return response()->json(['code' => '001', 'msg' => '此类别下有金价在使用，不能删除']);
            }

            $score = Score::where('goods_category_id', $id)->first();
            if (!empty($score)) {
                return response()->json(['code' => '001', 'msg' => '积分设置中正在使用该类别，不能删除']);
            }
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        GoodsCategory::where([['cp_id', $cp_id], ['is_del', 1]])->whereIn('id', $ids)->update(['is_del' => 2, 'del_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);


    }

    public function dodownload(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $row = [['类别名称', '柜组', '材质', '是否回收', '是否素金', '是否虚拟商品', '是否维护金价', '是否克算', '标价折扣', '备注']];
        $options = [
            'B' => GoodsCabinetgroup::where(['cp_id' => $cp_id, 'is_del' => 1])->get('cabinetgroup_name')->pluck('cabinetgroup_name')->toArray(),
            'C' => GoodsMetal::where(['cp_id' => $cp_id, 'is_del' => 1])->get('metal_name')->pluck('metal_name')->toArray(),
            'D' => ['是', '否'],
            'E' => ['是', '否'],
            'F' => ['是', '否'],
            'G' => ['是', '否'],
            'H' => ['是', '否'],
        ];
        $datawith = [
            'A' => '25',
            'B' => '25',
            'C' => '25',
            'D' => '25',
            'E' => '25',
            'F' => '25',
            'G' => '25',
            'H' => '25',
            'I' => '25',
            'J' => '50',
        ];
        $filename = '商品类别信息导入模板' . time() . '.xlsx';
        return Excel::download(new DownloadTemp($row, $options, $datawith), $filename);
    }

    /**
     * 上传导入，先调用uploadfile,返回地址调用该接口
     */
    public function doimport(Request $request)
    {
        $store_ids = $request->store_ids ?? [];
        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);
        if (count($store_ids) <= 0) {

            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }


        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $filepathname = $request->filepathname;

        if ($filepathname != '' && file_exists(storage_path() . $filepathname) && is_file(storage_path() . $filepathname)) {
            $file = storage_path() . $filepathname;
            $data = Excel::toArray(null, $file)[0];
            foreach ($store_ids as $store_id) {
                $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $cp_id])->first();
                if (!$storeinfo) {
                    return response()->json(['code' => '001', 'msg' => '无效门店参数']);
                }
            }

            $ins_data = [];
            foreach ($data as $key => $val) {
                if ($key == 0) { //表头跳过
                    if (count($val) != 10) {
                        return response()->json(['code' => '001', 'msg' => '导入数据格式错误']);
                    }
                    continue;
                }
                $val[1] = GoodsCabinetgroup::where(['cp_id' => $cp_id, 'is_del' => 1, 'cabinetgroup_name' => $val[1]])->value('id');
                if (!isset($val[2]) || empty($val[2])) {
                    return response()->json(['code' => '001', 'msg' => '材质未选择']);
                } else {
                    $val[2] = GoodsMetal::where(['cp_id' => $cp_id, 'is_del' => 1, 'metal_name' => $val[2]])->value('id');
                }

                $valdata = [
                    'cp_id' => $cp_id,
                    'category_name' => $val[0],
                    'goods_cabinetgroup_id' => intval($val[1]),
                    'goods_metal_id' => intval($val[2]) ?? 0,
                    'is_recovery' => $val[3] == '是' ? 1 : 2,
                    'is_sujin' => $val[4] == '是' ? 1 : 2,
                    'is_virtually' => $val[5] == '是' ? 1 : 2,
                    'is_maintenance_price' => $val[6] == '是' ? 1 : 2,
                    'is_gram' => $val[7] == '是' ? 1 : 2,
                    'price_discount' => $val[8] ? floatval($val[8]) : 0,
                    'remark' => $val[9] ? $val[9] : '',
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                    'create_at' => time(),
                    'update_at' => time(),
                ];

                if ($valdata['is_sujin'] != $valdata['is_gram']) {
                    return response()->json(['code' => '001', 'msg' => '是否素金和是否克算的值需要保持一致']);
                }

                if ($valdata['is_sujin'] == 1 && $valdata['is_virtually'] == 1) {
                    return response()->json(['code' => '001', 'msg' => '素金类不可为虚拟商品']);
                }

                foreach ($store_ids as $store_id) {
                    $cate = GoodsCategory::where([['category_name', $val[0]], ['store_id', $store_id], ['cp_id', $cp_id], ['is_del', 1]])->first();
                    if ($cate) {
                        $cate = $cate->toArray();
                        GoodsCategory::query()
                            ->where('id', $cate['id'])
                            ->update($valdata);
                    } else {
                        $item = $valdata;
                        $item['store_id'] = $store_id;
                        $ins_data[] = $item;
                    }

                }
            }
            GoodsCategory::insert($ins_data);
            return response()->json(['code' => '000', 'msg' => '数据导入成功']);
        } else {
            return response()->json(['code' => '001', 'msg' => '文件不存在'], 200);
        }
    }

    public function doexport(Request $request)
    {
        $list = GoodsCategory::getList($request)['list'];

        $exceldata = [];
        $row = [
            ['store_name' => '商品类别列表'],
            [
                'store_name' => '所属门店',
                'category_name' => '类别名称',
                'cabinetgroup_name' => '柜组',
                'goods_metal_name' => '材质',
                'is_recovery' => '是否回收',
                'is_sujin' => '是否素金',
                'is_virtually' => '是否虚拟商品',
                'is_maintenance_price' => '是否维护金价',
                'is_gram' => '是否克算',
                'price_discount' => '标价折扣',
                'remark' => '备注',
            ]];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'] ?? '',
                'category_name' => $val['category_name'],
                'cabinetgroup_name' => $val['cabinetgroupinfo']['cabinetgroup_name'] ?? '',
                'goods_metal_name' => $val['metalinfo']['metal_name'] ?? '',
                'is_recovery' => $val['is_recovery'] == 1 ? '是': '否',
                'is_sujin' => $val['is_recovery'] == 1 ? '是' : '否',
                'is_virtually' => $val['is_virtually'] == 1 ? '是' : '否',
                'is_maintenance_price' => $val['is_maintenance_price'] == 1 ? '是' : '否',
                'is_gram' => $val['is_gram'] == 1 ? '是' : '否',
                'price_discount' => $val['price_discount'] ?? 0,
                'remark' => $val['remark'] ?? '',
            ];
        }

        $filename = '商品类别信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata,[],[],false), $filename);
    }
}
